package com.example.hrsystem.workflow;

import android.app.Application;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.hrsystem.data.repository.ApprovalRepository;
import com.example.hrsystem.workflow.engine.ApprovalWorkflowEngine;
import com.example.hrsystem.workflow.model.ApprovalRequest;
import com.example.hrsystem.workflow.model.BusinessTripRequest;
import com.example.hrsystem.workflow.model.LeaveRequest;
import com.example.hrsystem.workflow.model.OvertimeRequest;
import com.example.hrsystem.workflow.model.ProcessInstance;
import com.example.hrsystem.workflow.model.WorkflowTask;

import java.util.ArrayList;
import java.util.List;

/**
 * 审批功能的ViewModel类
 * 处理审批相关的业务逻辑
 */
public class ApprovalViewModel extends AndroidViewModel {
    private final ApprovalRepository approvalRepository;
    private final ApprovalWorkflowEngine workflowEngine;
    
    // LiveData对象用于UI观察
    private MutableLiveData<List<ApprovalRequest>> allApprovalRequests;
    private MutableLiveData<List<WorkflowTask>> pendingTasks;
    private MutableLiveData<Boolean> isLoading;
    private MutableLiveData<String> errorMessage;
    private MutableLiveData<Boolean> operationSuccess;

    public ApprovalViewModel(Application application) {
        super(application);
        this.approvalRepository = new ApprovalRepository(application);
        this.workflowEngine = new ApprovalWorkflowEngine(application);
        this.allApprovalRequests = new MutableLiveData<>();
        this.pendingTasks = new MutableLiveData<>();
        this.isLoading = new MutableLiveData<>(false);
        this.errorMessage = new MutableLiveData<>();
        this.operationSuccess = new MutableLiveData<>();
    }

    // 获取LiveData引用
    public LiveData<List<ApprovalRequest>> getAllApprovalRequests() {
        return allApprovalRequests;
    }

    public LiveData<List<WorkflowTask>> getPendingTasks() {
        return pendingTasks;
    }

    public LiveData<Boolean> getIsLoading() {
        return isLoading;
    }

    public LiveData<String> getErrorMessage() {
        return errorMessage;
    }

    public LiveData<Boolean> getOperationSuccess() {
        return operationSuccess;
    }

    // 请假申请相关方法
    public void submitLeaveRequest(LeaveRequest leaveRequest, int approverId) {
        try {
            isLoading.setValue(true);
            
            // 保存请假申请
            approvalRepository.saveLeaveRequest(leaveRequest);
            
            // 启动审批流程
            long processInstanceId = workflowEngine.startApprovalProcess(
                    leaveRequest, "leave_approval", approverId);
            
            // 更新审批状态 - 修复类型转换问题
            leaveRequest.setProcessInstanceId((int) processInstanceId);
            approvalRepository.updateLeaveRequest(leaveRequest);
            
            operationSuccess.setValue(true);
        } catch (Exception e) {
            errorMessage.setValue("提交请假申请失败: " + e.getMessage());
            operationSuccess.setValue(false);
        } finally {
            isLoading.setValue(false);
        }
    }

    public List<LeaveRequest> getLeaveRequestsByApplicant(int applicantId) {
        return approvalRepository.getLeaveRequestsByApplicantId(applicantId);
    }

    public LeaveRequest getLeaveRequestById(int id) {
        return approvalRepository.getLeaveRequestById(id);
    }

    // 加班申请相关方法
    public void submitOvertimeRequest(OvertimeRequest overtimeRequest, int approverId) {
        try {
            isLoading.setValue(true);
            
            // 保存加班申请
            approvalRepository.saveOvertimeRequest(overtimeRequest);
            
            // 启动审批流程
            long processInstanceId = workflowEngine.startApprovalProcess(
                    overtimeRequest, "overtime_approval", approverId);
            
            // 更新审批状态 - 修复类型转换问题
            overtimeRequest.setProcessInstanceId((int) processInstanceId);
            approvalRepository.updateOvertimeRequest(overtimeRequest);
            
            operationSuccess.setValue(true);
        } catch (Exception e) {
            errorMessage.setValue("提交加班申请失败: " + e.getMessage());
            operationSuccess.setValue(false);
        } finally {
            isLoading.setValue(false);
        }
    }

    public List<OvertimeRequest> getOvertimeRequestsByApplicant(int applicantId) {
        return approvalRepository.getOvertimeRequestsByApplicantId(applicantId);
    }

    public OvertimeRequest getOvertimeRequestById(int id) {
        return approvalRepository.getOvertimeRequestById(id);
    }

    // 出差申请相关方法
    public void submitBusinessTripRequest(BusinessTripRequest businessTripRequest, int approverId) {
        try {
            isLoading.setValue(true);
            
            // 保存出差申请
            approvalRepository.saveBusinessTripRequest(businessTripRequest);
            
            // 启动审批流程
            long processInstanceId = workflowEngine.startApprovalProcess(
                    businessTripRequest, "business_trip_approval", approverId);
            
            // 更新审批状态
            // 修复类型转换问题
            businessTripRequest.setProcessInstanceId((int) processInstanceId);
            approvalRepository.updateBusinessTripRequest(businessTripRequest);
            
            operationSuccess.setValue(true);
        } catch (Exception e) {
            errorMessage.setValue("提交出差申请失败: " + e.getMessage());
            operationSuccess.setValue(false);
        } finally {
            isLoading.setValue(false);
        }
    }

    public List<BusinessTripRequest> getBusinessTripRequestsByApplicant(int applicantId) {
        return approvalRepository.getBusinessTripRequestsByApplicantId(applicantId);
    }

    public BusinessTripRequest getBusinessTripRequestById(int id) {
        return approvalRepository.getBusinessTripRequestById(id);
    }

    // 审批操作相关方法
    public void approveTask(long taskId, int approverId, String comment) {
        try {
            isLoading.setValue(true);
            
            boolean success = workflowEngine.handleApprovalTask(taskId, approverId, "approve", comment);
            
            if (success) {
                // 更新对应审批请求的状态
                updateApprovalRequestStatus(taskId, "APPROVED");
                operationSuccess.setValue(true);
            } else {
                errorMessage.setValue("审批失败，请稍后重试");
                operationSuccess.setValue(false);
            }
        } catch (Exception e) {
            errorMessage.setValue("审批操作失败: " + e.getMessage());
            operationSuccess.setValue(false);
        } finally {
            isLoading.setValue(false);
        }
    }

    public void rejectTask(long taskId, int approverId, String comment) {
        try {
            isLoading.setValue(true);
            
            boolean success = workflowEngine.handleApprovalTask(taskId, approverId, "reject", comment);
            
            if (success) {
                // 更新对应审批请求的状态
                updateApprovalRequestStatus(taskId, "REJECTED");
                operationSuccess.setValue(true);
            } else {
                errorMessage.setValue("拒绝失败，请稍后重试");
                operationSuccess.setValue(false);
            }
        } catch (Exception e) {
            errorMessage.setValue("拒绝操作失败: " + e.getMessage());
            operationSuccess.setValue(false);
        } finally {
            isLoading.setValue(false);
        }
    }

    // 获取审批任务相关方法
    public void loadApprovalTasks(int userId) {
        try {
            isLoading.setValue(true);
            List<WorkflowTask> tasks = workflowEngine.getApprovalTasks(userId);
            pendingTasks.setValue(tasks);
        } catch (Exception e) {
            errorMessage.setValue("加载审批任务失败: " + e.getMessage());
            pendingTasks.setValue(new ArrayList<>());
        } finally {
            isLoading.setValue(false);
        }
    }

    public List<ProcessInstance> getUserProcessInstances(int userId) {
        return workflowEngine.getUserProcessInstances(userId);
    }

    public ProcessInstance getProcessInstance(long processInstanceId) {
        return workflowEngine.getProcessInstance(processInstanceId);
    }

    public WorkflowTask getTaskById(long taskId) {
        return workflowEngine.getTaskById(taskId);
    }

    /**
     * 根据任务ID更新对应审批请求的状态
     */
    private void updateApprovalRequestStatus(long taskId, String status) {
        // 获取任务
        WorkflowTask task = workflowEngine.getTaskById(taskId);
        if (task == null) return;
        
        // 获取流程实例
        ProcessInstance instance = workflowEngine.getProcessInstance(task.getProcessInstanceId());
        if (instance == null) return;
        
        // 这里简化处理，实际应用中可能需要通过更复杂的方式获取对应的审批请求
        // 根据任务类型更新对应的审批请求状态
        // 例如，可以从任务的业务键或内容中解析出审批请求ID
    }

    /**
     * 获取待审批的请假申请
     */
    public List<LeaveRequest> getPendingLeaveRequests(int approverId) {
        return approvalRepository.getPendingLeaveRequestsByApproverId(approverId);
    }

    /**
     * 获取待审批的加班申请
     */
    public List<OvertimeRequest> getPendingOvertimeRequests(int approverId) {
        return approvalRepository.getPendingOvertimeRequestsByApproverId(approverId);
    }

    /**
     * 获取待审批的出差申请
     */
    public List<BusinessTripRequest> getPendingBusinessTripRequests(int approverId) {
        return approvalRepository.getPendingBusinessTripRequestsByApproverId(approverId);
    }
}